package org.yeruyi.common.util;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * Author:Yeruyi
 * Date:2017/11/15
 * Version:v1.0
 * Scope:
 * 2017年11月15日 新增对assert文件复制sd卡方法
 */
public class FileUtil {

    private static final String TAG = "[FileUtil]";

    /**
     * 复制asset文件到指定目录
     *
     * @param oldPath asset下的路径
     * @param newPath SD卡下保存路径
     */
    public static boolean CopyAssets(Context context, String oldPath, String newPath, String fileName) {
        try {
            String assetFileNames[] = context.getAssets().list(oldPath);// 获取assets目录下的所有文件及目录名
            if (assetFileNames.length > 0) {
                // 目录
                File file = new File(newPath);
                file.mkdirs();
                for (String assetFileName : assetFileNames) {
                    CopyAssets(context, oldPath, newPath, assetFileName);
                }
            } else {
                // 文件
                // 复制文件前先创建下文件吧
                File saveFile = new File(newPath + fileName);
                Log.d(TAG, "CopyAssets: 文件是否存在："+ saveFile.exists());
                if (!saveFile.exists()){
                    boolean result = saveFile.getParentFile().mkdirs();
                    Log.d(TAG, "CopyAssets: [创建文件1]："+ result);
                    boolean result2 = saveFile.createNewFile();
                    Log.d(TAG, "CopyAssets: [创建文件2]："+ result2);
                }
                InputStream is = context.getAssets().open(oldPath + fileName);
                FileOutputStream fos = new FileOutputStream(new File(newPath + fileName));
                byte[] buffer = new byte[1024];
                int byteCount = 0;
                while ((byteCount = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, byteCount);
                }
                fos.flush();
                is.close();
                fos.close();
            }
            return true;
        } catch (Exception e) {
            Log.e(TAG, "CopyAssets: 复制assets文件夹进入[" + newPath + "]异常", e);
            return false;
        }
    }
}
